package com.zxy.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxy.common.result.Result;
import com.zxy.mapper.ClueMapper;
import com.zxy.mapper.ClueTrackRecordMapper;
import com.zxy.pojo.entity.Clue;
import com.zxy.pojo.entity.ClueTrackRecord;
import com.zxy.pojo.vo.ClueTrackRecordVo;
import com.zxy.service.ClueTrackRecordService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ClueTrackRecordServiceImpl extends ServiceImpl<ClueTrackRecordMapper, ClueTrackRecord> implements ClueTrackRecordService {

    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;

    @Autowired
    private ClueMapper clueMapper;

    @Autowired
    private HttpServletRequest request;

    /**
     * 跟进记录信息
     * @param clueTrackRecordVo
     * @return
     */
    @Override
    @Transactional
    public Result add(ClueTrackRecordVo clueTrackRecordVo) {
        log.info("添加线索跟进记录: {}", clueTrackRecordVo);

        // 从session中获取当前用户名
        String currentUsername = (String) request.getSession().getAttribute("username");
        if (currentUsername == null) {
            currentUsername = "admin";
        }

        // 存储跟进记录
        ClueTrackRecord clueTrackRecord = new ClueTrackRecord();
        BeanUtils.copyProperties(clueTrackRecordVo, clueTrackRecord);
        clueTrackRecord.setNextTime(clueTrackRecordVo.getNextTime());
        clueTrackRecord.setCreateBy(currentUsername);
        clueTrackRecordMapper.insert(clueTrackRecord);

        // 更新线索信息
        Clue clue = clueMapper.selectClueById(clueTrackRecordVo.getClueId());
        if (clue != null) {
            // 更新线索状态为2（跟进中）
            clue.setStatus("2");
            
            // 更新意向学科、下次跟进时间等信息
            if (clueTrackRecordVo.getSubject() != null) {
                clue.setSubject(clueTrackRecordVo.getSubject());
            }
            if (clueTrackRecordVo.getLevel() != null) {
                clue.setLevel(clueTrackRecordVo.getLevel());
            }
            if (clueTrackRecordVo.getNextTime() != null) {
                clue.setNextTime(clueTrackRecordVo.getNextTime());
            }
            clue.setUpdateTime(new Date());
            clueMapper.updateClue(clue);
        }

        return Result.success();
    }

    @Override
    public List<ClueTrackRecord> listByClueId(Long clueId) {
        return clueTrackRecordMapper.selectByClueId(clueId);
    }

}
